<template>
  <div class="shipping-management">
    <div class="page-header">
      <h2>物流管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="物流名称">
          <el-input v-model="searchForm.shippingName" placeholder="请输入物流名称" clearable />
        </el-form-item>
        <el-form-item label="物流类型">
          <el-select v-model="searchForm.shippingType" placeholder="请选择物流类型" clearable>
            <el-option label="包邮" :value="1" />
            <el-option label="满额包邮" :value="2" />
            <el-option label="指定地区包邮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态">
          <el-select v-model="searchForm.shippingState" placeholder="请选择状态" clearable>
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已暂停" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchShipping">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增物流
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="shippingList" v-loading="loading" stripe>
        <el-table-column prop="shippingId" label="物流ID" width="80" />
        <el-table-column prop="shippingName" label="物流名称" width="200" />
        <el-table-column prop="shippingType" label="物流类型" width="120">
          <template #default="{ row }">
            {{ getShippingTypeText(row.shippingType) }}
          </template>
        </el-table-column>
        <el-table-column prop="shippingCon" label="物流条件" width="200" />
        <el-table-column prop="shippingScope" label="适用范围" width="120">
          <template #default="{ row }">
            {{ getShippingScopeText(row.shippingScope) }}
          </template>
        </el-table-column>
        <el-table-column prop="shippingState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateType(row.shippingState)">
              {{ getStateText(row.shippingState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editShipping(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteShipping(row.shippingId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑物流' : '新增物流'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="shippingForm" :rules="shippingRules" ref="shippingFormRef" label-width="120px">
        <el-form-item label="物流名称" prop="shippingName">
          <el-input v-model="shippingForm.shippingName" placeholder="请输入物流名称" />
        </el-form-item>
        <el-form-item label="物流类型" prop="shippingType">
          <el-select v-model="shippingForm.shippingType" placeholder="请选择物流类型">
            <el-option label="包邮" :value="1" />
            <el-option label="满额包邮" :value="2" />
            <el-option label="指定地区包邮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流条件" prop="shippingCon">
          <el-input v-model="shippingForm.shippingCon" type="textarea" placeholder="请输入物流条件" />
        </el-form-item>
        <el-form-item label="适用范围" prop="shippingScope">
          <el-select v-model="shippingForm.shippingScope" placeholder="请选择适用范围">
            <el-option label="全平台" :value="1" />
            <el-option label="指定商品" :value="2" />
            <el-option label="指定分类" :value="3" />
            <el-option label="指定地区" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态" prop="shippingState">
          <el-select v-model="shippingForm.shippingState" placeholder="请选择状态">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已暂停" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="shippingForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="shippingForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { shippingApi } from '@/api/shipping'

// 响应式数据
const loading = ref(false)
const shippingList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const shippingFormRef = ref()

// 搜索表单
const searchForm = reactive({
  shippingName: '',
  shippingType: null,
  shippingState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 物流表单
const shippingForm = reactive({
  shippingId: null,
  shippingName: '',
  shippingType: null,
  shippingCon: '',
  shippingScope: null,
  shippingState: null,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const shippingRules = {
  shippingName: [
    { required: true, message: '请输入物流名称', trigger: 'blur' }
  ],
  shippingType: [
    { required: true, message: '请选择物流类型', trigger: 'change' }
  ],
  shippingCon: [
    { required: true, message: '请输入物流条件', trigger: 'blur' }
  ],
  shippingScope: [
    { required: true, message: '请选择适用范围', trigger: 'change' }
  ],
  shippingState: [
    { required: true, message: '请选择物流状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取物流类型文本
const getShippingTypeText = (type) => {
  const typeMap = {
    1: '包邮',
    2: '满额包邮',
    3: '指定地区包邮'
  }
  return typeMap[type] || '未知'
}

// 获取适用范围文本
const getShippingScopeText = (scope) => {
  const scopeMap = {
    1: '全平台',
    2: '指定商品',
    3: '指定分类',
    4: '指定地区'
  }
  return scopeMap[scope] || '未知'
}

// 获取状态类型
const getStateType = (state) => {
  const stateMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return stateMap[state] || 'info'
}

// 获取状态文本
const getStateText = (state) => {
  const stateMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束',
    3: '已暂停'
  }
  return stateMap[state] || '未知'
}

// 搜索物流
const searchShipping = async () => {
  loading.value = true
  try {
    const response = await shippingApi.findShipping(searchForm)
    if (response.code === 200) {
      shippingList.value = response.data || []
      pagination.total = shippingList.value.length
    }
  } catch (error) {
    console.error('搜索物流失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    shippingName: '',
    shippingType: null,
    shippingState: null
  })
  searchShipping()
}

// 编辑物流
const editShipping = (row) => {
  isEdit.value = true
  Object.assign(shippingForm, row)
  showAddDialog.value = true
}

// 删除物流
const deleteShipping = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个物流活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await shippingApi.deleteShipping(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchShipping()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除物流失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await shippingFormRef.value.validate()

    const response = isEdit.value
      ? await shippingApi.updateShipping(shippingForm)
      : await shippingApi.insertShipping(shippingForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchShipping()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(shippingForm, {
    shippingId: null,
    shippingName: '',
    shippingType: null,
    shippingCon: '',
    shippingScope: null,
    shippingState: null,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  shippingFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchShipping()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchShipping()
}

// 初始化
onMounted(() => {
  searchShipping()
})
</script>

<style scoped>
.shipping-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>